﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.HealthChecks;
using RabbitMQ.Client;
using TimeTickService.Configs;

namespace TimeTickService.Extensions.HealthCheck
{
    public static class RabbitMqHealthCheckExtensions
    {
        public static HealthCheckBuilder AddRabbitMQCheck(this HealthCheckBuilder builder, string name,
            IConnectionFactory connectionFactory)
        {
            return AddRabbitMQCheck(builder, name, connectionFactory, builder.DefaultCacheDuration);
        }

        public static HealthCheckBuilder AddRabbitMQCheck(this HealthCheckBuilder builder, string name, IConnectionFactory connectionFactory, TimeSpan cacheDuration)
        {
            builder.AddCheck($"RabbitMQCheck({name}", async () =>
            {
                try
                {
                    using (var connection = connectionFactory.CreateConnection())
                    {
                        using (var channel = connection.CreateModel())
                        {
                            if (channel.IsOpen)
                                return HealthCheckResult.Healthy($"RabbitMQCheck({name}): Healthy");
                            return HealthCheckResult.Unhealthy($"RabbitMQCheck({name}): Unhealthy");
                        }
                    }
                }
                catch (Exception ex)
                {
                    return HealthCheckResult.Unhealthy($"RabbitMQCheck({name}): Exception during check: {ex.GetType().FullName}");
                }
            }, cacheDuration);

            return builder;
        }
    }
}
